package com.lhy.admin.service;

import com.lhy.admin.common.mvcplus.service.SimpleService;
import com.lhy.admin.mapper.FileMappingMapper;
import com.lhy.admin.model.FileMapping;
import com.lhy.admin.util.AuthUtil;
import com.lhy.admin.util.FileUtil;
import com.lhy.admin.util.QiniuUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class FileMappingService extends SimpleService<FileMappingMapper, FileMapping> {

    @Autowired
    QiniuUtil qiniuUtil;

    @Autowired
    AuthUtil authUtil;


    public List<FileMapping> findParentsById (Integer parent) {
        return this.list(new FileMapping().setParent(parent));
    }

    public List<FileMapping> listFileMappingIncludeChildren (Integer id) {
        return baseMapper.listFileMappingIncludeChildren(id);
    }

    /**
     * deleteFileMapping
     * <p/>
     * 删除文件，同时也回到七牛云上删除
     *
     * @param keys
     * @return void
     * @throws
     * @date 2018/7/30 14:50
     */
    public void deleteOssFile (String... keys) {
        if ( keys == null ) {
            return;
        }
        qiniuUtil.delete(keys);
    }

    public void deleteFileMappings (List<Integer> ids) {
        baseMapper.deleteBatchIds(ids);
    }

    public void deleteFileMapping (Integer id) {
        List<FileMapping> fileMappings = listFileMappingIncludeChildren(id);
        String[] keys = fileMappings.stream().filter(f -> f.getFolder() == 0).map(FileMapping::getKey).toArray(String[]::new);
        List<Integer> ids = fileMappings.stream().map(FileMapping::getId).collect(Collectors.toList());
        //删除数据库记录包含子目录
        this.deleteFileMappings(ids);
        this.deleteOssFile(keys);
    }

    public FileMapping createFileMapping (FileMapping mapping) {
        // 创建文件时, 补充缺失的属性
        if ( mapping.getFolder() == null || mapping.getFolder() == 0 ) {
            if ( mapping.getUrl() == null ) {
                if ( mapping.getKey() == null ) {
                    throw new NullPointerException("文件地址(url)不能为空!");
                }
                mapping.setUrl(qiniuUtil.buildUrl(mapping.getKey()));
            }
            if ( mapping.getExt() == null ) {
                mapping.setExt(FileUtil.getType(mapping.getName()));
            }
            mapping.setFolder(0);
        }
        Integer id = null;
        try {
            id = authUtil.getUser().getId();
        } catch (Exception e) {
            log.trace("",e);
        }
        mapping.setCreator(id);
        this.save(mapping);
        return mapping;
    }


    public String uploadToken () {
        return qiniuUtil.uploadToken();
    }


}
